package com.lijia.ffmpeg4android.nerdlauncher.fragment;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.actionbarsherlock.app.SherlockListFragment;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class NerdLauncherFragment extends SherlockListFragment {
	public static final String TAG = "NerdLauncherFragment";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent startupIntent = new Intent(Intent.ACTION_MAIN);
		startupIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		
		PackageManager pm = getSherlockActivity().getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(startupIntent, 0);
		Log.i(TAG, "I've found " + activities.size() + " activities");
		
		Collections.sort(activities,new Comparator<ResolveInfo>() {
			PackageManager pm = getSherlockActivity().getPackageManager();
			@Override
			public int compare(ResolveInfo a, ResolveInfo b) {
				return String.CASE_INSENSITIVE_ORDER.compare(
						a.loadLabel(pm).toString(), 
						b.loadLabel(pm).toString()
						);
			}
		});
		
		ArrayAdapter<ResolveInfo> adapter = new ArrayAdapter<ResolveInfo>(
				getSherlockActivity(),android.R.layout.simple_list_item_1,activities) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				PackageManager pm = getSherlockActivity().getPackageManager();
				View v = super.getView(position, convertView, parent);
				TextView tv = (TextView)v;
				ResolveInfo ri = getItem(position);
				tv.setText(ri.loadLabel(pm));
				return v;
			}
		};
		
		setListAdapter(adapter);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		ResolveInfo resolveInfo = (ResolveInfo)l.getAdapter().getItem(position);
		ActivityInfo activityInfo = resolveInfo.activityInfo;
		if(activityInfo == null) return;
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.setClassName(activityInfo.applicationInfo.name, activityInfo.name);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}
	
	
}
